package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    /**
     * 执行的逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径
        String path = request.getURI().getPath();
        //判断是否需要鉴权,判断是否有login请求头，如果有不需要

        //判断地址是否含有“/login"
        if (path.contains("/login")){
            //如果包含，直接放行
            return chain.filter(exchange);
        }
        //不包含，验证token
        //请求对象中获取请求头
        String token = request.getHeaders().getFirst("token");
        //没有token，返回错误
        if(StringUtils.isEmpty(token)){
            //返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //响应给客户端，不在网后端转发
            return response.setComplete();
        }
        //如果有token，验证token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //token是否有效（过期）
            int result =AppJwtUtil.verifyToken(claimsBody);
            //-1 或 0 代表有效，如果有效，提取用户ID
            if (result == -1||result ==0){
                //获取token中的userId
                Object userId = claimsBody.get("userId");
                //将id放入请求头，将带有id的请求转发给后端
                request.mutate().header("userId",userId.toString());
                //转发给后端
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            //过期会抛出异常
            log.error(e.getMessage());
        }
        //没有token返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //响应给客户端，不在网后端转发
        return response.setComplete();
    }

    /**
     * 过滤器执行的顺序，越小越优先
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
